<?php
namespace App\Services\Trade;

use Illuminate\Support\Facades\DB;
use App\Models\Base\DistrictModel;
use App\Models\Base\UserModel;
use App\Models\Trade\Shop\ShopModel;
use App\Models\Trade\Supply\SupplyModel;
use App\Models\Trade\Supply\SupplyCountVisitModel;
use App\Models\Trade\Common\FishKindModel;
use App\Models\Trade\Common\FishUnitSizeModel;
use App\Models\Trade\Common\FishUnitPriceModel;

class SupplyService
{

    /**
     * 获取查询字段
     *
     * @return string
     */
    protected function makeFields()
    {
        return implode(',', [
            'd.id,d.sn,d.shop_id,d.kind_id,fk.name as kind_name',
            'd.title,d.status,d.size_min,d.size_max,uz.name as size_unit_name',
            'd.sale_type,d.sale_pre,d.price_type,d.price,up.name as price_unit_name',
            'd.stock,p.name as province_name,c.name as city_name,d.contact_name',
            'd.img,d.desc,d.desc_tag,d.created,d.updated,IFNULL(dc.pv,0) as pv'
        ]);
    }

    /**
     * 获取查询字段（列表）
     * 
     * @return string
     */
    protected function makeFieldList()
    {
        return implode(',', [
            $this->makeFields(),
            'u.avatar,s.verify_classify,s.verify_name,s.verify_type'
        ]);
    }
    
    /**
     * 获取查询字段（详情）
     * 
     * @return string
     */
    protected function makeFieldDetail()
    {
        return implode(',', [
            $this->makeFields(),
            'd.contact_mobile,a.name as area_name,t.name as town_name,d.address'
        ]);
    }
    
    /**
     * 获取列表数据
     * 
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @param array $param 其他参数
     * @param int $order 排序
     * @return array(\Illuminate\Support\Collection, int)
     */
    public function selectList($page = 1, $pageSize = 50, $param = array(), $order = SupplyModel::ORDER_DEFAULT)
    {
        $queryList = SupplyModel::dbTable('d');
        $queryCount = clone $queryList;
        
        $where = array();
        // 店铺
        if (isset($param['shop_id']) && ! empty($param['shop_id'])) {
            $where[] = ['d.shop_id', $param['shop_id']];
        }
        // 排除ID
        if (isset($param['id']) && ! empty($param['id'])) {
            if (is_array($param['id'])) {
                $queryList->whereNotIn('d.id', $param['id']);
                $queryCount->whereNotIn('d.id', $param['id']);
            } else {
                $where[] = ['d.id', '<>', $param['id']];
            }
        }
        // 品种
        if (isset($param['kind_id']) && ! empty($param['kind_id'])) {
            $where[] = ['d.kind_id', $param['kind_id']];
        }
        // 省份
        if (isset($param['province']) && ! empty($param['province'])) {
            $where[] = ['d.province', $param['province']];
        }
        // 城市
        if (isset($param['city']) && ! empty($param['city'])) {
            $where[] = ['d.city', $param['city']];
        }
        // 认证状态
        if (isset($param['verify']) && $param['verify'] == SupplyModel::VERIFY_TRUE) {
            $queryList->whereNotNull('s.verify_classify');
            
            $queryCount->whereNotNull('s.verify_classify');
            $queryCount->leftJoin(ShopModel::TABLENAME . ' as s', 's.id', '=', 'd.shop_id');
        }
        // 品种名、标题（搜索）
        if (isset($param['keyword']) && ! empty($param['keyword'])) {
            $queryCount->leftJoin(FishKindModel::TABLENAME . ' as fk', 'fk.id', '=', 'd.kind_id');
            $queryCount->where(function ($query) use ($param) {
                $query->where('d.title', 'like', '%' . $param['keyword'] . '%')
                    ->orWhere('fk.name', 'like', '%' . $param['keyword'] . '%');
            });
            $queryList->where(function ($query) use ($param) {
                $query->where('d.title', 'like', '%' . $param['keyword'] . '%')
                    ->orWhere('fk.name', 'like', '%' . $param['keyword'] . '%');
            });
        }
        $where[] = ['d.status', SupplyModel::STATUS_DEFAULT];
        
        // 查询数量
        $count = $queryCount->where($where)->count();
        // 构造语句
        $queryList->select(DB::raw($this->makeFieldList()))
            ->leftJoin(FishKindModel::TABLENAME . ' as fk', 'fk.id', '=', 'd.kind_id')
            ->leftJoin(FishUnitSizeModel::TABLENAME . ' as uz', 'uz.id', '=', 'd.size_unit_id')
            ->leftJoin(FishUnitPriceModel::TABLENAME . ' as up', 'up.id', '=', 'd.price_unit_id')
            ->leftJoin(DistrictModel::TABLENAME . ' as p', 'p.id', '=', 'd.province')
            ->leftJoin(DistrictModel::TABLENAME . ' as c', 'c.id', '=', 'd.city')
            ->leftJoin(ShopModel::TABLENAME . ' as s', 's.id', '=', 'd.shop_id')
            ->leftJoin(UserModel::TABLENAME . ' as u', 'u.id', '=', 's.user_id')
            ->leftJoin(SupplyCountVisitModel::TABLENAME . ' as dc', 'dc.supply_id', '=', 'd.id')
            ->where($where)
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize);
        // 排序
        switch ($order) {
            case SupplyModel::ORDER_PRICE_ASC:
                $queryList->orderBy('d.price', 'asc');
                break;
            case SupplyModel::ORDER_PRICE_DESC:
                $queryList->orderBy('d.price', 'desc');
                break;
            default:
                $queryList->orderBy('d.updated', 'desc');
                break;
        }
        // 查询数据
        $collection = $queryList->get();

        return array(
            $collection,
            $count
        );
    }

    /**
     * 获取详情数据
     * 
     * @param int $id 数据ID
     * @return \Illuminate\Support\Collection
     */
    public function findDetail($id)
    {
        $where[] = ['d.id', $id];
        return SupplyModel::dbTable('d')->select(DB::raw($this->makeFieldDetail()))
            ->leftJoin(FishKindModel::TABLENAME . ' as fk', 'fk.id', '=', 'd.kind_id')
            ->leftJoin(FishUnitSizeModel::TABLENAME . ' as uz', 'uz.id', '=', 'd.size_unit_id')
            ->leftJoin(FishUnitPriceModel::TABLENAME . ' as up', 'up.id', '=', 'd.price_unit_id')
            ->leftJoin(DistrictModel::TABLENAME . ' as p', 'p.id', '=', 'd.province')
            ->leftJoin(DistrictModel::TABLENAME . ' as c', 'c.id', '=', 'd.city')
            ->leftJoin(DistrictModel::TABLENAME . ' as a', 'a.id', '=', 'd.area')
            ->leftJoin(DistrictModel::TABLENAME . ' as t', 't.id', '=', 'd.town')
            ->leftJoin(SupplyCountVisitModel::TABLENAME . ' as dc', 'dc.supply_id', '=', 'd.id')
            ->where($where)
            ->get();
    }

    /**
     * 获取详情店铺数据
     * 
     * @param int $id 数据ID
     * @return \Illuminate\Support\Collection
     */
    public function findDetailShop($id)
    {
        $item = SupplyModel::findById($id, ['shop_id'])->shift();

        $shopService = new ShopService();
        return $shopService->findDetail($item['shop_id']);
    }

    /**
     * 获取热门品种
     * 
     * @param int $timed 天
     * @param int $pageSize
     * @return \Illuminate\Support\Collection
     */
    public function selectHotKind($timed, $pageSize)
    {
        return collect(DB::select('call proc_trade_pub_hot_select(:type,:timed,:pageSize)', [
            'type' => 1,
            'timed' => $timed * 86400,
            'pageSize' => $pageSize
        ]));
    }

    /**
     * 获取详情推荐列表
     *
     * @param int $id
     * @param int $pageSize
     * @return array(\Illuminate\Support\Collection, int)
     */
    public function selectDatailMoers($id, $pageSize = 5)
    {
        $item = SupplyModel::findById($id, ['kind_id'])->shift();
    
        return $this->selectList(1, $pageSize, [
            'kind_id' => $item['kind_id'],
            'id' => $id
        ]);
    }
}